package com.dolphin.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfiguration {

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager() {

        UserDetails user = User.builder()
                .username("dolphin")
                .password("$2a$10$x/C1A15hwS3dDDvGnrjLQOuS5m9S30RyYKV9uaSSNQ44IZAdy6Ozu")
                .roles("USER")
                .build();
        return new InMemoryUserDetailsManager(user);
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        //自定义配置
        http
                .authorizeHttpRequests(request ->
                        request.requestMatchers("/mylogin").permitAll()
                                .anyRequest().authenticated()
                )
                .formLogin(Customizer.withDefaults())
                .httpBasic(Customizer.withDefaults())
                .csrf(AbstractHttpConfigurer::disable);

        //拦截范围
//        http.authorizeHttpRequests(request -> request.anyRequest().authenticated());
//        //展示登录表单‘
//        http.formLogin(Customizer.withDefaults());
//        //认证方式采用基础的认证方式（用户名+密码）
//        http.httpBasic(Customizer.withDefaults());
        //返回新的过滤器链
        return http.build();
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("dolphin"));
    }


}
